/**
 * @desc 地图位置选择器组件
 */
import { EnvironmentOutlined, SearchOutlined } from '@ant-design/icons';
import { AutoComplete, Button, Input, Modal, Space, message } from 'antd';
import { useCallback, useRef, useState } from 'react';
import { BaseMap } from 'tlbs-map-react';

// 位置信息类型
interface LocationInfo {
  lat: number;
  lng: number;
  address: string;
}

// 组件Props类型
interface MapLocationPickerProps {
  /** 是否显示弹窗 */
  visible: boolean;
  /** 关闭弹窗回调 */
  onCancel: () => void;
  /** 确认选择回调 */
  onConfirm: (location: LocationInfo) => void;
  /** 地图API Key */
  apiKey: string;
  /** 初始位置 */
  initialLocation?: LocationInfo;
  /** 弹窗标题 */
  title?: string;
  /** 弹窗宽度 */
  width?: number;
}

const MapLocationPicker: React.FC<MapLocationPickerProps> = ({
  visible,
  onCancel,
  onConfirm,
  apiKey = 'RMIBZ-6TTKK-S4LJ3-ATFPK-YNMBE-34BPQ',
  initialLocation,
  title = '选择位置',
  width = 800,
}) => {
  // 地图实例引用
  const mapRef = useRef<any>();
  const markerRef = useRef<any>();

  // 状态管理
  const [center, setCenter] = useState(
    initialLocation
      ? { lat: initialLocation.lat, lng: initialLocation.lng }
      : { lat: 39.908823, lng: 116.39747 },
  );
  const [selectedLocation, setSelectedLocation] = useState<LocationInfo | null>(
    initialLocation || null,
  );
  const [searchValue, setSearchValue] = useState('');
  const [searchResults, setSearchResults] = useState<any[]>([]);

  /**
   * 搜索地点
   */
  const searchPlaces = useCallback(
    async (keyword: string) => {
      if (!keyword.trim()) {
        setSearchResults([]);
        return;
      }

      try {
        const response = await fetch(
          `/map-api/ws/place/v1/suggestion?keyword=${encodeURIComponent(
            keyword,
          )}&key=${apiKey}`,
        );

        if (!response.ok) {
          throw new Error('搜索请求失败');
        }

        const data = await response.json();

        if (data.status === 0 && data.data) {
          const results = data.data.map((item: any, index: number) => ({
            id: `${index}`,
            title: item.title,
            address: item.address,
            location: {
              lat: item.location.lat,
              lng: item.location.lng,
            },
          }));
          setSearchResults(results);
        } else {
          message.error('搜索失败，请检查API Key或网络连接');
          setSearchResults([]);
        }
      } catch (error) {
        console.error('搜索地点失败:', error);
        message.error('搜索失败，请稍后重试');
        setSearchResults([]);
      }
    },
    [apiKey],
  );

  /**
   * 处理搜索输入变化
   */
  const handleSearchChange = useCallback(
    (value: string) => {
      setSearchValue(value);
      if (value.trim()) {
        searchPlaces(value);
      } else {
        setSearchResults([]);
      }
    },
    [searchPlaces],
  );

  /**
   * 选择搜索结果
   */
  const handleSelectResult = useCallback((result: any) => {
    setCenter(result.location);
    setSelectedLocation({
      lat: result.location.lat,
      lng: result.location.lng,
      address: result.address,
    });
    setSearchValue(result.title);
    setSearchResults([]);
  }, []);

  /**
   * 获取位置名称（逆地理编码）
   */
  const getLocationName = useCallback(
    async (lat: number, lng: number) => {
      try {
        const response = await fetch(
          `/map-api/ws/geocoder/v1/?location=${lat},${lng}&key=${apiKey}&get_poi=1`,
        );

        if (!response.ok) {
          throw new Error('逆地理编码请求失败');
        }

        const data = await response.json();

        if (data.status === 0 && data.result) {
          const result = data.result;
          // 优先使用POI名称，如果没有则使用地址
          const locationName =
            result?.formatted_addresses?.standard_address ||
            result.address ||
            '未知位置';
          return locationName;
        } else {
          return '未知位置';
        }
      } catch (error) {
        console.error('获取位置名称失败:', error);
        return '未知位置';
      }
    },
    [apiKey],
  );

  /**
   * 创建标记点
   */
  const createMarker = useCallback(
    (lat: number, lng: number, title: string = '') => {
      if (!mapRef.current) return;

      // 清除之前的标记点和信息窗口
      if (markerRef.current) {
        markerRef.current.setMap(null);
        if ((markerRef.current as any).infoWindow) {
          (markerRef.current as any).infoWindow.close();
        }
      }

      // 创建新的标记点
      const marker = new (window as any).TMap.MultiMarker({
        map: mapRef.current,
        geometries: [
          {
            id: 'marker',
            styleId: 'marker',
            position: new (window as any).TMap.LatLng(lat, lng),
          },
        ],
      });

      markerRef.current = marker;

      // 如果有标题，创建信息窗口
      if (title) {
        const infoWindow = new (window as any).TMap.InfoWindow({
          map: mapRef.current,
          position: new (window as any).TMap.LatLng(lat, lng),
          content: `
          <div style=" font-size: 12px; max-width: 200px;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
            <div style="font-weight: bold; color: #1890ff; margin-bottom: 2px;">
              📍 ${title}
            </div>
          </div>
        `,
          offset: { x: 0, y: -30 },
        });

        // 存储信息窗口引用
        (markerRef.current as any).infoWindow = infoWindow;
      }
    },
    [],
  );

  /**
   * 地图点击事件处理
   */
  const handleMapClick = useCallback(
    async (event: any) => {
      const { lat, lng } = event.latLng;

      // 更新地图中心到点击位置
      setCenter({ lat, lng });

      // 先创建标记点（无标题）
      createMarker(lat, lng);

      // 显示加载状态
      setSelectedLocation({
        lat,
        lng,
        address: '正在获取位置信息...',
      });

      // 获取位置名称
      const locationName = await getLocationName(lat, lng);

      // 更新选中位置
      setSelectedLocation({
        lat,
        lng,
        address: locationName,
      });

      // 重新创建标记点（带标题）
      createMarker(lat, lng, locationName);
    },
    [getLocationName, createMarker],
  );

  /**
   * 地图初始化完成事件
   */
  const onMapInited = useCallback(() => {
    console.log('地图初始化完成');
    // 如果有初始位置，创建标记点
    if (initialLocation) {
      createMarker(initialLocation.lat, initialLocation.lng);
    }
  }, [initialLocation, createMarker]);

  /**
   * 确认选择
   */
  const handleConfirm = useCallback(() => {
    if (!selectedLocation) {
      message.warning('请先选择位置');
      return;
    }
    onConfirm(selectedLocation);
  }, [selectedLocation, onConfirm]);

  /**
   * 取消选择
   */
  const handleCancel = useCallback(() => {
    setSelectedLocation(initialLocation || null);
    setSearchValue('');
    setSearchResults([]);
    // 清除标记点和信息窗口
    if (markerRef.current) {
      markerRef.current.setMap(null);
      if ((markerRef.current as any).infoWindow) {
        (markerRef.current as any).infoWindow.close();
      }
      markerRef.current = null;
    }
    onCancel();
  }, [initialLocation, onCancel]);

  return (
    <Modal
      title={
        <Space>
          <EnvironmentOutlined />
          <span>{title}</span>
        </Space>
      }
      open={visible}
      onCancel={handleCancel}
      width={width}
      footer={[
        <Button key="cancel" onClick={handleCancel}>
          取消
        </Button>,
        <Button
          key="confirm"
          type="primary"
          onClick={handleConfirm}
          disabled={!selectedLocation}
        >
          确认选择
        </Button>,
      ]}
      destroyOnClose
    >
      <div style={{ height: 500 }}>
        {/* 搜索框 */}
        <div style={{ marginBottom: 16 }}>
          <AutoComplete
            value={searchValue}
            onChange={handleSearchChange}
            options={searchResults.map((result) => ({
              value: result.title,
              label: (
                <div>
                  <div style={{ fontWeight: 'bold' }}>{result.title}</div>
                  <div style={{ fontSize: '12px', color: '#666' }}>
                    {result.address}
                  </div>
                </div>
              ),
              result,
            }))}
            onSelect={(value, option) => {
              if (option.result) {
                handleSelectResult(option.result);
              }
            }}
            style={{ width: '100%' }}
          >
            <Input
              prefix={<SearchOutlined />}
              placeholder="搜索地点..."
              allowClear
            />
          </AutoComplete>
        </div>

        {/* 地图容器 */}
        <div style={{ height: 'calc(100% - 40px)' }}>
          <BaseMap
            ref={mapRef}
            apiKey={apiKey}
            control={{
              zoom: {
                position: 'topRight',
                className: 'tmap-zoom-control-box',
                numVisible: true,
              },
            }}
            options={{
              center,
              zoom: 15,
              showControl: true,
            }}
            onClick={handleMapClick}
            onMapInited={onMapInited}
          ></BaseMap>
        </div>
      </div>
    </Modal>
  );
};

export default MapLocationPicker;
